package com.finance.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.finance.entity.GoodsOrder;
import com.finance.mapper.GoodsOrderMapper;
import com.finance.service.GoodsOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * C02
 * 商品订单数据Service实现类
 */
@Slf4j
@Service
public class GoodsOrderServiceImpl extends ServiceImpl<GoodsOrderMapper, GoodsOrder> implements GoodsOrderService {

    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int processOrders(List<Map<String, String>> records, String searchDate, boolean forceUpdate) {
        return processOrders(records, searchDate, forceUpdate, null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int processOrders(List<Map<String, String>> records, String searchDate, boolean forceUpdate, String cinemaId) {
        if (records == null || records.isEmpty()) {
            return 0;
        }

        // 如果不是强制更新，先检查数据是否存在
        if (!forceUpdate) {
            long count = lambdaQuery()
                    .eq(GoodsOrder::getSearchDate, searchDate)
                    .eq(GoodsOrder::getCinemaId, cinemaId)
                    .count();
            if (count > 0) {
                log.info("C02数据已存在，searchDate: {}, cinemaId: {}, 跳过处理", searchDate, cinemaId);
                return 0;
            }
        } else {
            // 如果是强制更新，先删除指定日期的数据
            lambdaUpdate()
                    .eq(GoodsOrder::getSearchDate, searchDate)
                    .eq(GoodsOrder::getCinemaId, cinemaId)
                    .remove();
        }

        List<GoodsOrder> orderList = new ArrayList<>();
        for (Map<String, String> record : records) {
            try {
                // 必填字段验证
                if (!validateRequiredFields(record)) {
                    log.warn("必填字段缺失，跳过处理记录: {}", record);
                    continue;
                }

                GoodsOrder order = new GoodsOrder();

                // 设置影院ID
                order.setCinemaId(cinemaId);
                //销售时间,影院名称,售订单号,退订单号,销售类型,销售渠道,销售员工号,销售员,大类,卖品名称,套餐别名
                // 日期时间类型转换
                String saleTimeStr = record.get("销售时间");
                if (StringUtils.hasText(saleTimeStr)) {
                    order.setSaleTime(LocalDateTime.parse(saleTimeStr, DATE_TIME_FORMATTER));
                }

                String pickupTimeStr = record.get("取货时间");
                if (StringUtils.hasText(pickupTimeStr)) {
                    order.setPickupTime(LocalDateTime.parse(pickupTimeStr, DATE_TIME_FORMATTER));
                }

                // 数字类型转换
                String saleQuantityStr = record.get("销售数量");
                if (StringUtils.hasText(saleQuantityStr)) {
                    order.setSaleQuantity(Integer.parseInt(saleQuantityStr));
                }

                String originalPriceStr = record.get("原价");
                if (StringUtils.hasText(originalPriceStr)) {
                    order.setOriginalPrice(new BigDecimal(originalPriceStr));
                }

                String actualPriceStr = record.get("实际售价");
                if (StringUtils.hasText(actualPriceStr)) {
                    order.setActualPrice(new BigDecimal(actualPriceStr));
                }

                String payAmountStr = record.get("支付金额");
                if (StringUtils.hasText(payAmountStr)) {
                    order.setPayAmount(new BigDecimal(payAmountStr));
                }

                String discountAmountStr = record.get("优惠金额");
                if (StringUtils.hasText(discountAmountStr)) {
                    order.setDiscountAmount(new BigDecimal(discountAmountStr));
                }

                String thirdPartyDiscountAmountStr = record.get("第三方优惠金额");
                if (StringUtils.hasText(thirdPartyDiscountAmountStr)) {
                    order.setThirdPartyDiscountAmount(new BigDecimal(thirdPartyDiscountAmountStr));
                }
                // 字符串类型字段
                if (StringUtils.hasText(record.get("影院名称"))) {
                    order.setCinemaName(record.get("影院名称"));
                }
                if (StringUtils.hasText(record.get("售订单号"))) {
                    order.setSaleOrderNo(record.get("售订单号"));
                }
                String s = record.get("退订单号");
                if (StringUtils.hasText(s)) {
                    order.setRefundOrderNo(s);
                }
                if (StringUtils.hasText(record.get("销售类型"))) {
                    order.setSaleType(record.get("销售类型"));
                }
                if (StringUtils.hasText(record.get("销售渠道"))) {
                    order.setSaleChannel(record.get("销售渠道"));
                }
                if (StringUtils.hasText(record.get("销售员工号"))) {
                    order.setSellerEmployeeNo(record.get("销售员工号"));
                }
                if (StringUtils.hasText(record.get("操作员"))) {
                    order.setSeller(record.get("操作员"));
                }
                if (StringUtils.hasText(record.get("大类"))) {
                    order.setGoodsCategoryName(record.get("大类"));
                }
                if (StringUtils.hasText(record.get("卖品名称"))) {
                    order.setGoodsName(record.get("卖品名称"));
                }
                if (StringUtils.hasText(record.get("套餐别名"))) {
                    order.setPackageAlias(record.get("套餐别名"));
                }
                // 卖品编码,销售数量,单位,原价,实际售价,套餐内容,支付工具,支付金额,优惠信息,优惠金额
                if (StringUtils.hasText(record.get("卖品编码"))) {
                    order.setGoodsCode(record.get("卖品编码"));
                }
                if (StringUtils.hasText(record.get("单位"))) {
                    order.setUnit(record.get("单位"));
                }
                if (StringUtils.hasText(record.get("套餐内容"))) {
                    order.setPackageContent(record.get("套餐内容"));
                }
                if (StringUtils.hasText(record.get("支付工具"))) {
                    order.setPayTool(record.get("支付工具"));
                }
                if (StringUtils.hasText(record.get("优惠信息"))) {
                    order.setDiscountInfo(record.get("优惠信息"));
                }
                // 活动ID,活动名称,补贴方,销售工作站,销售地点,库存扣减地点,取货时间,取货员工号
                if (StringUtils.hasText(record.get("活动ID"))) {
                    order.setActivityCode(record.get("活动ID"));
                }
                if (StringUtils.hasText(record.get("活动名称"))) {
                    order.setActivityName(record.get("活动名称"));
                }
                if (StringUtils.hasText(record.get("补贴方"))) {
                    order.setSubsidyParty(record.get("补贴方"));
                }
                if (StringUtils.hasText(record.get("销售工作站"))) {
                    order.setSaleWorkstation(record.get("销售工作站"));
                }
                if (StringUtils.hasText(record.get("销售地点"))) {
                    order.setSaleLocation(record.get("销售地点"));
                }
                if (StringUtils.hasText(record.get("库存扣减地点"))) {
                    order.setInventoryLocation(record.get("库存扣减地点"));
                }
                if (StringUtils.hasText(record.get("取货员工号"))) {
                    order.setPickupEmployeeNo(record.get("取货员工号"));
                }
                // 取货员,取货工作站,外部流水号,第三方订单号,券模板名称,退货渠道编码,退货渠道,影院国家编码,影院所属区域
                if (StringUtils.hasText(record.get("取货员"))) {
                    order.setPickupEmployee(record.get("取货员"));
                }
                if (StringUtils.hasText(record.get("取货工作站"))) {
                    order.setPickupWorkstation(record.get("取货工作站"));
                }
                if (StringUtils.hasText(record.get("外部流水号"))) {
                    order.setExternalSerialNo(record.get("外部流水号"));
                }
                if (StringUtils.hasText(record.get("第三方订单号"))) {
                    order.setThirdPartyOrderNo(record.get("第三方订单号"));
                }
                if (StringUtils.hasText(record.get("券模板名称"))) {
                    order.setCouponTemplateName(record.get("券模板名称"));
                }
                if (StringUtils.hasText(record.get("退货渠道编码"))) {
                    order.setRefundChannelCode(record.get("退货渠道编码"));
                }
                if (StringUtils.hasText(record.get("退货渠道"))) {
                    order.setRefundChannel(record.get("退货渠道"));
                }
                if (StringUtils.hasText(record.get("影院国家编码"))) {
                    order.setCinemaCode(record.get("影院国家编码"));
                }
                if (StringUtils.hasText(record.get("影院所属区域"))) {
                    order.setCinemaArea(record.get("影院所属区域"));
                }
                // 会员卡号,优惠券码,大类编码,套餐编码,支付工具编码,支付序号,销售渠道编码,券模版编码,影城所属区域编码
                if (StringUtils.hasText(record.get("会员卡号"))) {
                    order.setMemberCardNo(record.get("会员卡号"));
                }
                if (StringUtils.hasText(record.get("优惠券码"))) {
                    order.setCouponCode(record.get("优惠券码"));
                }
                if (StringUtils.hasText(record.get("大类编码"))) {
                    order.setGoodsCategoryCode(record.get("大类编码"));
                }
                if (StringUtils.hasText(record.get("套餐编码"))) {
                    order.setPackageCode(record.get("套餐编码"));
                }
                if (StringUtils.hasText(record.get("支付工具编码"))) {
                    order.setPayToolCode(record.get("支付工具编码"));
                }
                if (StringUtils.hasText(record.get("支付序号"))) {
                    order.setPaySequence(record.get("支付序号"));
                }
                if (StringUtils.hasText(record.get("销售渠道编码"))) {
                    order.setSaleChannelCode(record.get("销售渠道编码"));
                }
                if (StringUtils.hasText(record.get("券模版编码"))) {
                    order.setCouponTemplateCode(record.get("券模版编码"));
                }
                if (StringUtils.hasText(record.get("影城所属区域编码"))) {
                    order.setCinemaAreaCode(record.get("影城所属区域编码"));
                }
                // 会员ID,手机号,商户订单号,第三方支付流水号,第三方优惠信息,第三方优惠金额
                if (StringUtils.hasText(record.get("会员ID"))) {
                    order.setMemberId(record.get("会员ID"));
                }
                if (StringUtils.hasText(record.get("手机号"))) {
                    order.setMobile(record.get("手机号"));
                }
                if (StringUtils.hasText(record.get("商户订单号"))) {
                    order.setMerchantOrderNo(record.get("商户订单号"));
                }
                if (StringUtils.hasText(record.get("第三方支付流水号"))) {
                    order.setThirdPartyPayNo(record.get("第三方支付流水号"));
                }
                if (StringUtils.hasText(record.get("第三方优惠信息"))) {
                    order.setThirdPartyDiscountInfo(record.get("第三方优惠信息"));
                }
                order.setSearchDate(searchDate);

                // 设置新增字段
                if (StringUtils.hasText(record.get("活动类型"))) {
                    order.setActivityType(record.get("活动类型"));
                }
                if (StringUtils.hasText(record.get("发卡影城编码"))) {
                    order.setIssueCinemaCode(record.get("发卡影城编码"));
                }
                if (StringUtils.hasText(record.get("发卡影城名称"))) {
                    order.setIssueCinemaName(record.get("发卡影城名称"));
                }
                if (StringUtils.hasText(record.get("发券影城编码"))) {
                    order.setIssueCouponCinemaCode(record.get("发券影城编码"));
                }
                if (StringUtils.hasText(record.get("发券影城名称"))) {
                    order.setIssueCouponCinemaName(record.get("发券影城名称"));
                }
                if (StringUtils.hasText(record.get("一级分类"))) {
                    order.setFirstCategory(record.get("一级分类"));
                }
                if (StringUtils.hasText(record.get("二级分类"))) {
                    order.setSecondCategory(record.get("二级分类"));
                }
                if (StringUtils.hasText(record.get("三级分类"))) {
                    order.setThirdCategory(record.get("三级分类"));
                }

                orderList.add(order);
            } catch (Exception e) {
                log.error("处理商品订单记录失败: {}", record, e);
            }
        }

        try {
            if (!orderList.isEmpty()) {
                return saveBatch(orderList) ? orderList.size() : 0;
            }
            return 0;
        } catch (Exception e) {
            log.error("批量保存商品订单数据失败", e);
            throw e;
        }
    }

    /**
     * 验证必填字段
     *
     * @param record 数据记录
     * @return 是否通过验证
     */
    private boolean validateRequiredFields(Map<String, String> record) {
        // 必填字段列表
        String[] requiredFields = {
                "销售时间",
                "影院名称"
        };

        for (String field : requiredFields) {
            if (!StringUtils.hasText(record.get(field))) {
                log.warn("必填字段[{}]为空", field);
                return false;
            }
        }

        return true;
    }
} 